package cn.tuling.proxy;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * Created on 2020/12/2.
 *
 * @author qiyang.
 * 描述：
 */
public class MainTest {

    public static void main(String[] args) {

        /**
         * 类加载器
         * 类型
         * 委托处理类
         */

//        ClassLoader classLoader = ICalculator.class.getClassLoader();
//
//        Class[] interfaces = new Class[]{ICalculator.class};
//
//        InvocationHandler handler = new MyInvocationHandler(new Calculator());
//
//        ICalculator calculator = (ICalculator) Proxy.newProxyInstance(classLoader, interfaces, handler);
//
//        int result = calculator.add(1, 2);
//
//        System.out.println("result = " + result);

        ICalculator calculator = (ICalculator) createProxy(new Calculator());

        int result = calculator.add(1, 2);

    }

    /**
     * 抽象出jdk动态代理对象生成公共方法
     *
     * @return
     */
    public static Object createProxy(Object needProxy) {

        ClassLoader classLoader = needProxy.getClass().getClassLoader();

        Class[] interfaces = needProxy.getClass().getInterfaces();

        InvocationHandler handler = new MyInvocationHandler(needProxy);

        Object o = Proxy.newProxyInstance(classLoader, interfaces, handler);

        return o;
    }

}
